<script lang="ts" setup>
	import { ref, onMounted, computed } from 'vue';
	import { getAllTeacehrs, getAllTeacehrsPage, getTeacehr, createAppoint, getQuestions, getAdvisorys, getAdvisorysByTime } from '@/api/psychology/appointment.js'
	import { userInfo } from '@/store/Pinia/userInfo.js'

	const cates = ["选择时间预约", "选择老师预约"]

	let curNow = ref('0');
	let timeShow = ref(true);
	let teachers = ref<any[]>([]);
	let theTeacher = ref({});
	let allQuestions = ref({});
	let time = ref('');
	let number = ref('');
	const answers = ref<any[]>([]);
	const littleShowPopup = ref(false)
	const showPopup = ref(false)
	let fullDate = ref();
	const userInfoModel = userInfo()


	onMounted(() => {
		if (userInfoModel.data.id == null) {
			uni.navigateTo({
				url: '/pages/login/index'
			})
		}
		const currentDate = new Date(); // 获取当前日期
		const year = currentDate.getFullYear(); // 获取年份
		const month = String(currentDate.getMonth() + 1).padStart(2, '0'); // 获取月份，并补零
		const day = String(currentDate.getDate()).padStart(2, '0'); // 获取日期，并补零
		fullDate.value = `${year}-${month}-${day}`;
		selectDate.value = fullDate.value
		getAll(fullDate.value);
	});

	//分页方法
	const current = ref(0)
	const totalData = ref(0)
	const pageSize = ref(12)
	const pageNum = computed(() => {
		return Math.ceil(totalData.value / pageSize.value)
	})
	const pageList = computed(() => {
		let list = []
		for (let i = 1; i <= pageNum.value; i++) {
			list.push(i);
		}
		return [...list]
	})
	const changePage = (e) => {
		current.value = e.current
		getAll(fullDate.value);
	}

	const getAll = (time = null) => {
		let item = {
			"workDate": time,
			current: current.value,
			size: pageSize.value
		}
		getAllTeacehrsPage(item).then((res) => {
			teachers.value = res?.data.data.records;
			totalData.value = res?.data.data.total;
		}).catch((error) => {
		})
	};

	// 自动保存 
	const exit = () => {
		littleShowPopup.value = true;
	}
	const goBack = () => {
		littleShowPopup.value = false;
	}

	interface createItem {
		"cnId" ?: String | number,
		"stuId" ?: String,
		"consRoomId" ?: String,
		"reservationDate" ?: String,
		"reservationEndTime" ?: String,
		"reservationStartTime" ?: String,
		"consAdvisoryState" ?: String,
		"stuPhone" ?: String,
		"problemList" ?: any,
		"consCnDutyId" ?: String | number
	}

	const createItem = ref<createItem>({})

	const no = () => {
		selectTimeId.value = null
		littleShowPopup.value = false;
		showPopup.value = false;
		createItem.value = {}
	}

	const objReduce = computed(() => {//将对象列表中，每个对象的某个属性提出来作为key值，并且重复的合并
		return function (obj, keyName) {
			let groupedObject = obj.reduce((accumulator, currentObject) => {
				const key = currentObject[keyName];
				// 如果当前key还不存在，创建一个新数组
				if (!accumulator[key]) {
					accumulator[key] = [];
				}
				// 将当前对象添加到对应的数组中
				accumulator[key].push(currentObject);
				return accumulator;
			}, {});
			return groupedObject;
		}
	})

	const selectDate = ref('')
	const sectionChange = (index : any) => {
		curNow.value = index;
		switch (index) {
			case 0:
				timeShow.value = true;
				uni.navigateTo({
					url: '/pages/appointment/index'
				})
				break;
			case 1:
				uni.navigateTo({
					url: '/pages/appointment/apmByCnUser/apmByCnUser'
				})
				break;
			case 2:
				uni.navigateTo({
					url: '/pages/appointment/record/index'
				})
				break;

		}
	}

	const selectedChange = (e) => {
		console.log('hh')
		fullDate.value = e.fullDate;
		getAll(fullDate.value)

	}

	let isEmpty = computed<boolean>(() => {
		return teachers.value.every((teacher : any) => teacher.date !== fullDate.value);
	});

	const teacherList = computed(() => {
		let it = []
		it = teachers.value.filter((item) => {

			if (item.cnUser != null) {
				return item
			}
		})
		return [...it]
	})

	const getTime = computed(() => {
		return function (time) {
			if (time != void 0) {
				var dateObject = new Date(time);

				var timeString = dateObject.toLocaleTimeString('zh', { hour12: false });

				return `${dateObject.getHours()}:${(dateObject.getMinutes() < 10 ? '0' : '') + dateObject.getMinutes()}`
			} else {
				return time
			}
		}
	})

	const formmatTime = computed(() => {//将2023-12-14转换成12/14
		return function (tiem) {
			let dateString = tiem;

			// 创建日期对象
			let dateObject = new Date(dateString);

			// 提取月份和日期
			let month = (dateObject.getMonth() + 1).toString().padStart(2, '0'); // 月份是从0开始，所以需要加1
			let day = dateObject.getDate().toString().padStart(2, '0');

			// 创建新的格式
			let newFormat = `${month}/${day}`;
			return newFormat
		}
	})
	const calendarShow = ref(false)
	const schedulingList = ref([])
	const schedulingListLen = ref(0)


	const selectTimeId = ref(0)
	const selectTimeValue = ref('')
	const selectTime = (e) => {
		selectTimeId.value = e.id
		theTeacher.value = e
	}

	const toAppoint = (item) => {
		if (item?.consCnDutyState == 1) {
			uni.showToast({
				title: '当前时段已被预定',
				icon: 'none'
			})
		} else {
			uni.navigateTo({
				url: '/pages/appointment/apmForm/apmForm?id=' + item.id
			})
		}
	}

	const backToMain = () => {
		uni.reLaunch({
			url: '/pages/index/home/home'
		})
	}

	// const flagTest = ref(false)

	const flag = ref(false)
	const showDate = () => {
		flag.value = true
	}
	const timer = ref(null)
	const handleEnd = () => {
		timer.value.resetTime()
	}
</script>

<template>
<articleTable ref="timer"></articleTable>
	<img :src="'@/../static/img/appoint/appoint-bg.svg'"
		style="opacity: 0.2;width: 45%;position: absolute;top: 50%;right: 0;" />
	<Navigator :fixed="true" background-color="transparent" status-bar left-icon="back" left-text="返回" title="心理预约"
		@clickLeft="backToMain" customLeft class="absolute">
	</Navigator>
	<view @touchend="handleEnd" class="wh100p body flex-column " style="justify-content: center; align-items: center;">
		<view class="w100p h100p flex-column" style="padding:1% 2%;box-sizing: border-box;">
			<view class="flex-between w100p column-center">
				<view style="width:600px" class="mt30">
					<view class=" gui-dark-bg-level-3  gui-margin-top custom" style="padding:10px 0">
						<gui-switch-navigation :items="[{id:0,name:'选择时间预约'},{id:1,name:'选择老师预约'},{id:2,name:'预约记录'}]"
							textAlign="center" :isCenter="false" activeDirection="center" :size="0" :margin="20"
							padding="10rpx" activeLineHeight="6rpx" :scorllAnimation="true" activeFontSize="34px"
							fontSize="32px" lineHeight="46px" :titleClass="['color56A5FF']" :width="1800"
							@change="sectionChange"></gui-switch-navigation>
					</view>
				</view>
				<view class="flex column-center mt10">
					<view class="ml24">
						<view class="flex column-center" @click="flag = true">
							<view class="font20 mr16 colorffffff">{{fullDate}}</view>
							<button type="default" class="gui-button gui-bg-primary gui-noborder vAlign-center "
								style="border-radius:50rpx;height:35px;">
								<text class="gui-icons gui-color-white gui-button-text " style="padding:0 20px"><text
										style="margin-right:10px;line-height:35px">请选择日期</text>&#xe6d1; </text>
							</button>
						</view>
						<view class="bgfffff calendar-outBox absolute mt14" :class="flag? 'show':'hide'"
							style="width: 350px;height: 330px;background: linear-gradient(180deg, #49BEFF 0%, #3186FC 100%), #FAFAFA;color: white;border-radius: 10px;padding: 10px;right: 2%;z-index: 3;">
							<view class=" flex-column">
								<view class="w100p flex-end ">
									<view style="padding: 0 10px;" @click="flag = false">
										<u-icon name="close" color="#2979ff" size="18"></u-icon>
									</view>
								</view>
								<view class="calendar-box pt12">
									<zzx-calendar @selected-change="selectedChange"></zzx-calendar>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>

			<view v-if="teacherList.length<1" class="flex-center " style="margin-top: 5%;">
				<gui-empty>
					<template v-slot:img>
						<view class="gui-flex gui-rows gui-justify-content-center">
							<text class="gui-icons gui-empty-icon gui-color-white font72">&#xe644;</text>
						</view>
					</template>
					<template v-slot:text>
						<text class=" gui-block gui-text-center gui-margin-top gui-color-white font32">暂无数据</text>
					</template>
				</gui-empty>
			</view>
			<view v-else class="flex-center w100p" style="flex-wrap: wrap;z-index: 2;height: 90%;overflow: hidden;">
				<view v-for="(item,index) of teacherList" :key="index"
					style="width: 24%;margin-left: 15px; min-width: 300px;height: 250px;" @click="  toAppoint(item)"
					class="click-scale consultant-item mt20">
					<view class="appoint-box" style="height: 100%;overflow: hidden;">
						<view class="flex item-top" style="height: 76%;">
							<view class="avatar">
								<image class="avatar" :src="item?.cnUser?.avatar??'../../static/img/bigavatar.png'"
									mode="aspectFill">
								</image>
							</view>
							<view class="flex-column wh100p">
								<view class="flex-between column-center">
									<view class="flex column-center" style="width: 70%;">
										<view class="teacher-name ">{{item?.cnUser?.realName??'暂无'}}</view>
										<text :style="{ color: 'white' }" style="margin-left: 15%;font-size: 24px;">
											{{item?.cnUser?.sex ?? ''}}</text>
									</view>
									<text :style="{ color: item && item.consCnDutyState === 1 ? '#3572ff' : 'white' }">
										{{item?.consCnDutyState==1?'无名额':'可预定'}}</text>
								</view>
								<view class="teacher-dec mt12 " style="overflow: scroll;"><text
										style="text-overflow: ellipsis;font-size: 22px;">{{item?.cnUser?.remark!=null&&item?.cnUser?.remark!="" ?item?.cnUser?.remark:'老师温柔体贴，有不开心的事情就来向我倾诉吧。'}}</text>
								</view>
							</view>
						</view>
						<view class="flex item-bottom">
							<view> <text class="cnName colorFFBF0D"
									style="font-size: 18px;font-weight: 600;line-height: 40rpx;"
									v-show="item?.workStartTime!=void 0 && curNow!=1">时间段：<text
										class="colorffffff">{{getTime(item?.workStartTime)}}-{{getTime(item?.workEndTime)}}</text></text>
							</view>
							<view><text class="cnName colorFFBF0D"
									style="font-size: 18px;font-weight: 600;line-height: 40rpx;padding-right: 20px;">地址：<text
										class="colorffffff">{{item?.consRoom?.name||'暂无'}}</text></text>
							</view>
						</view>
					</view>
				</view>
				<i v-for="(item,index) of 4" :key="index"
					style="width: 24%;margin-left: 15px; min-width: 300px;height: 250px;"></i>
			</view>
			<view class="flex w100p">

			</view>
			<view class="custom flex-center " style="height: 6%;color: white;align-items: flex-end;">
				<uni-pagination :total="totalData" prev-text="上一页" next-text="下一页" :pageSize="pageSize"
					@change="changePage" :current="current" />
			</view>
		</view>
	</view>
</template>

<style>
	.body {
		background: linear-gradient(90deg, #0078BB 0%, #003E94 100%);

	}

	/deep/.custom .zzx-calendar .calendar-days {
		height: 80%;
	}

	/deep/.custom .zzx-calendar .calendar-days .calendar-day {
		height: 50px;

	}

	/deep/.custom .gui-primary-text {
		color: white;
	}

	.colorfff {
		color: white;
	}

	.appoint-box {
		padding-top: 20px;
		justify-content: center;
		align-items: flex-start;
		/* flex: 1 0 0; */
		border-radius: 25px;
		background: linear-gradient(180deg, #49BEFF 0%, #3186FC 100%), #FAFAFA;
		box-sizing: border-box;
		margin-left: 10px;

	}

	.item-top {
		padding: 10px 32px;
		align-items: center;
		align-self: stretch;
		box-sizing: border-box;
	}

	.avatar {
		width: 100px;
		height: 100px;
		margin-right: 16px;
		border-radius: 50%;
	}

	.teacher-name {
		color: #FFF;
		font-family: PingFang SC;
		font-size: 32px;
		font-style: normal;
		font-weight: 600;
		line-height: normal;

	}

	.teacher-dec {
		color: #FFF;
		text-align: justify;
		font-family: PingFang SC;
		font-size: 24px;
		font-style: normal;
		font-weight: 400;
		line-height: normal;

	}

	.item-bottom {
		padding: 20px;
		justify-content: space-between;
		align-items: flex-start;
		align-self: stretch;
		border-radius: 0px 0px 8px 8px;
		background: #358DFD;
	}

	.calendar-outBox {
		transition: 0.5s;
		transition-timing-function: ease;

	}

	.show {
		opacity: 1;
	}

	.hide {
		opacity: 0;
		pointer-events: none;
		/* 使隐藏元素不响应点击事件 */
	}

	/deep/.custom .uni-pagination__num-tag {
		margin: 0 8px;
		font-size: 18px;
		padding: 0 10px;
	}

	/deep/.custom .uni-pagination__total {
		font-size: 18px;
		color: white;
		margin-right: 20px;
	}

	/deep/.custom .uni-pagination__child-btn {
		font-size: 18px;

	}
</style>